package xuanzhen.wx.service;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.Session;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.stereotype.Service;

import xuanzhen.wx.pojo.msg.resp.Article;
import xuanzhen.wx.pojo.msg.resp.NewsMessage;
import xuanzhen.wx.pojo.msg.resp.TextMessage;
import xuanzhen.wx.util.MsgUtil;
import xuanzhen.wx.util.SignUtil;
import xuanzhen.wx.util.WeixinUtil;
import xuanzhen.wx.util.fina.WxSet;
import xuanzhen.wx.pojo.AccessToken;
import xuanzhen.wx.pojo.Jsticket;
import xuanzhen.wx.pojo.WxUserMsg;

import net.sf.json.JSONObject;


/**
 * 核心服务类
 * 
 * @author liufeng
 * @date 2013-05-20
 */
@Service
public class CoreService {
	/**
	 * 处理微信发来的请求
	 * 
	 * @param request
	 * @return
	 */
	public static String processRequest(HttpServletRequest request) {
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "你很幸运，看到了世界上最帅的帅哥做的公众平台号！";

			// xml请求解析
			Map<String, String> requestMap = MsgUtil.parseXml(request);

			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			
			// 回复文本消息
		/*	TextMessage textMessage = new TextMessage();
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);*/
			//把（“yyyy-MM-dd HH:mm:ss”)转化为整数
		/*	textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(MsgUtil.RESP_MESSAGE_TYPE_TEXT);*/
			// 位0x0001被标志时，星标刚收到的消息  
			/*textMessage.setFuncFlag(0);*/
			 if (msgType.equals(MsgUtil.REQ_MESSAGE_TYPE_EVENT)) {
				// 事件类型
				String eventType = requestMap.get("Event");
				// 订阅
				if (eventType.equals(MsgUtil.EVENT_TYPE_SUBSCRIBE)) {
					respContent = "谢谢您的关注！";
				}
				// 取消订阅
				else if (eventType.equals(MsgUtil.EVENT_TYPE_UNSUBSCRIBE)) {
					// TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
				}
				
                }
				/*textMessage.setContent(respContent);
				respMessage = MsgUtil.textMessageToXml(textMessage);*/
			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return respMessage;
	}
	public void assembleT(){
		// 获取时间戳
				long timestamp = System.currentTimeMillis() / 1000;
				
				// 生成随机字符串
				String noncestr = RandomStringUtils.randomAlphanumeric(16);
			
	}
	/**
	 * 发送https请求获取acess_token
	 * @param code，网页授权后获取的
	 * @param state参数
	 * @return token对象
	 * @throws UnsupportedEncodingException
	 */
	//发送https请求获取acess_token
	public AccessToken getAccessToken(String code,String state) throws UnsupportedEncodingException{
		// TODO
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WxSet.APPID+"&secret="+WxSet.AppSecret+"&code="+code+"&grant_type=authorization_code";	
		//String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WxSet.APPID_TEST+"&secret="+WxSet.AppSecret_TEST+"&code="+code+"&grant_type=authorization_code";	
		JSONObject json= WeixinUtil.httpRequest(url,"GET",null);
		System.out.println(json.toString());
		System.out.println("begin");
		AccessToken at=new 	AccessToken();
		if(json.getString("access_token")!=null){
			at.setToken(json.getString("access_token")); 
		}
		if(json.getInt("expires_in")!=0){
			at.setExpiresIn(json.getInt("expires_in")); 
		}	
		if(json.getString("openid")!=null){
			at.setOpenid(json.getString("openid")); 
		}	
			
		return at;
		
	}
	/**
	 * 发送https请求获取acess_token1区别于网页授权
	 * @return 返回token对象
	 * @throws UnsupportedEncodingException
	 */
	public AccessToken getAccessTokenC() throws UnsupportedEncodingException{
		/*String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+WxSet.APPID+"&secret="+WxSet.AppSecret;*/	
		String s_url="https://wechat.car2go.cn/wxat";
		JSONObject json= WeixinUtil.httpRequest(s_url,"GET",null);
		System.out.println(json);
		AccessToken atc=new AccessToken();
			atc.setToken(json.getString("access_token")); 
			/*atc.setExpiresIn(json.getInt("expires_in")); */
		return atc;
		
	}
	/*public static void main(String[] args) {
		JSONObject json= WeixinUtil.httpRequest("https://wechat.car2go.cn/wxat","GET",null);
		System.out.println(json);
	}*/
	/**
	 * 发送https请求获取用户信息
	 * @param at 网页授权获取的token对象
	 * @return 微信用户信息对象
	 * @throws UnsupportedEncodingException
	 */
	public WxUserMsg catchUserMsg(AccessToken at) throws UnsupportedEncodingException{
		String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+at.getToken()+"&openid="+at.getOpenid()+"&lang=zh_CN";
		JSONObject json= WeixinUtil.httpRequest(url,"GET",null);
		WxUserMsg us =new WxUserMsg();
			us.setOpenid(json.getString("openid")); 
			us.setNickname(json.getString("nickname")); 
			us.setSex(json.getString("sex")); 
			us.setProvince(json.getString("province")); 
			us.setCity(json.getString("city")); 
			us.setCountry(json.getString("country"));    
			us.setHeadimgurl(json.getString("headimgurl")); 
			us.setPrivilege(json.getString("privilege")); 
		return us;
	}
	/**
	 * Dating静默授权不获取xinxi
	 */
	public String getUser(String Durl) throws UnsupportedEncodingException{
		String R_url= java.net.URLEncoder.encode(WxSet.DatingUri+Durl,"utf-8");
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WxSet.APPID+"&redirect_uri="+R_url+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
//		url= java.net.URLEncoder.encode(url,"utf-8");
		return url;
	}
	/**
	 * 发送https请求打开授权页面
	 * @return 需要跳转的授权页面路径
	 * @throws UnsupportedEncodingException
	 */
	public String getChrisRight() throws UnsupportedEncodingException{
		
		String R_url= java.net.URLEncoder.encode(WxSet.ChrisUri,"utf-8");
		String ur = "https://wechat.car2go.cn/wx/?exurl="+R_url+"&exscope=snsapi_userinfo";
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WxSet.APPID+"&redirect_uri="+R_url+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
//		url= java.net.URLEncoder.encode(url,"utf-8");
		return ur;
	}
	
	/**
	 * 发送https请求打开授权页面
	 * @return 需要跳转的授权页面路径
	 * @throws UnsupportedEncodingException
	 */
	public String getReserRight(String spread) throws UnsupportedEncodingException{
		
		String R_url= java.net.URLEncoder.encode(WxSet.ReserUri+"?spread="+spread,"utf-8");
		String ur = "https://wechat.car2go.cn/wx/?exurl="+R_url+"&exscope=snsapi_userinfo";
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WxSet.APPID+"&redirect_uri="+R_url+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
//		url= java.net.URLEncoder.encode(url,"utf-8");
		return ur;
	}
	/**
	 * 发送https请求打开授权页面
	 * @return 需要跳转的授权页面路径
	 * @throws UnsupportedEncodingException
	 */
	public String getUserRight() throws UnsupportedEncodingException{
		String R_url= java.net.URLEncoder.encode(WxSet.redirectUri,"utf-8");
		String ur = "https://wechat.car2go.cn/wx/?exurl="+R_url+"&exscope=snsapi_userinfo";
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WxSet.APPID+"&redirect_uri="+R_url+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
//		url= java.net.URLEncoder.encode(url,"utf-8");
		return ur;
	}
	/**
	 * 发送https请求打开授权页面
	 * @return 需要跳转的授权页面路径
	 * @throws UnsupportedEncodingException
	 */
	public String getCofeRight() throws UnsupportedEncodingException{
		String R_url= java.net.URLEncoder.encode(WxSet.redirectCofeUri,"utf-8");
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WxSet.APPID+"&redirect_uri="+R_url+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
//		url= java.net.URLEncoder.encode(url,"utf-8");
		return url;
	}
	/**
	 * 发送https请求打开授权页面
	 * @return 需要跳转的授权页面路径
	 * @throws UnsupportedEncodingException
	 */
	public String getReUserRight(String reNourl) throws UnsupportedEncodingException{
		/*String R_url= request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
		if (request.getQueryString() != null) {
			R_url += "?" + request.getQueryString();
		} 		*/
		String R_url= java.net.URLEncoder.encode(WxSet.recUri+reNourl,"utf-8");
		String ur = "https://wechat.car2go.cn/wx/?exurl="+R_url+"&exscope=snsapi_userinfo";
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WxSet.APPID+"&redirect_uri="+R_url+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
//		url= java.net.URLEncoder.encode(url,"utf-8");
		return ur;
	}
	/**
	 * 发送请求获取js_tiket
	 * @param at，授权token对象，与网页授权不同！
	 * @return js票
	 * @throws UnsupportedEncodingException
	 */
	public Jsticket getJsticket(AccessToken at) throws UnsupportedEncodingException{
		String url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+at.getToken()+"&type=jsapi";
		String s_url = "https://wechat.car2go.cn/wxjs";
		JSONObject json= WeixinUtil.httpRequest(s_url,"GET",null);
		System.out.println(json);
		Jsticket ticket=new Jsticket();
		/*ticket.setErrcode(json.getString("errcode"));
		ticket.setErrmsg(json.getString("errmsg"));*/
		/*ticket.setTicket(json.getString("ticket"));*/
		/*ticket.setExpiresIn(json.getInt("expires_in"));*/
		ticket.setTicket(json.getString("jsapi_ticket"));
		ticket.setAppId(json.getString("appId"));
		ticket.setNonceStr(json.getString("nonceStr"));
		ticket.setSignature(json.getString("signature"));
		ticket.setTimestamp(json.getString("timestamp"));
		ticket.setUrl(json.getString("nonceStr"));
		return ticket;
	}
	/**
	 * 发送请求获取js_tiket
	 * @param at，授权token对象，与网页授权不同！
	 * @return js票
	 * @throws UnsupportedEncodingException
	 */
	public Jsticket getmyJsticket(AccessToken at) throws UnsupportedEncodingException{
		// TODO
		String url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+at.getToken()+"&type=jsapi";
		JSONObject json= WeixinUtil.httpRequest(url,"GET",null);
		System.out.println(json);
		Jsticket ticket=new Jsticket();
		ticket.setErrcode(json.getString("errcode"));
		ticket.setErrmsg(json.getString("errmsg"));
		ticket.setTicket(json.getString("ticket"));
		ticket.setExpiresIn(json.getInt("expires_in"));
		return ticket;
	}
	public static void main(String[] args) {
		String url="https://wechat.car2go.cn/wxjs";
		JSONObject json= WeixinUtil.httpRequest(url,"GET",null);
		System.out.println(json);
	}
	/**
	 * 进行签名
	 * @param url引入jssdk的本网页全路径
	 * @param timestamp时间戳
	 * @param nonceStr随机字符串16
	 * @param ticket获取的js票
	 * @return 返回签名
	 */
	public String getSignature(String url, String timestamp, String nonceStr, String ticket){
		String sig=WeixinUtil.Signature(url, timestamp, nonceStr, ticket);
		return sig;
	}
	/** 
	 * 获取媒体文件 
	 *  
	 * @param accessToken 
	 *      接口访问凭证 
	 * @param media_id 
	 *      媒体文件id 
	 * */
	/*public static String downloadMedia(String mediaId,String accessTocken) { 
	  String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID"; 
	  requestUrl = requestUrl.replace("ACCESS_TOKEN", accessTocken).replace( 
	      "MEDIA_ID", mediaId); 
	  HttpURLConnection conn = null; 
	  try { 
	    URL url = new URL(requestUrl); 
	    conn = (HttpURLConnection) url.openConnection(); 
	    conn.setDoInput(true); 
	    conn.setRequestMethod("GET"); 
	    conn.setConnectTimeout(30000); 
	    conn.setReadTimeout(30000); 
	    BufferedInputStream bis = new BufferedInputStream( 
	        conn.getInputStream()); 
	    ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
	    byte[] buff = new byte[100];  
	    int rc = 0;  
	    while ((rc = bis.read(buff, 0, 100)) > 0) {  
	      swapStream.write(buff, 0, rc);  
	    }  
	    byte[] filebyte = swapStream.toByteArray();  
	    return PictureStore.getInstance().getImageServerUrl() + PictureStore.getInstance().store(filebyte); 
	  } catch (Exception e) { 
	    e.printStackTrace(); 
	  } finally { 
	    if(conn != null){ 
	      conn.disconnect(); 
	    } 
	  } 
	  return ""; 
	}*/
}
